package com.hspedu.reflection.calss;

import com.hspedu.Car;

import java.lang.reflect.Field;

/**
 * 演示Class 类常用方法
 */
public class Class2 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {

        String classFullPath = "com.hspedu.Car";
        //1、获取Car类 对应的 Class对象
        Class cls = Class.forName(classFullPath);

        //2、输出 cls
        System.out.println(cls);
        System.out.println(cls.getClass());

        //3、得到包名
        System.out.println(cls.getPackage().getName());

        //4、得到类名
        System.out.println(cls.getName());

        //5、通过 cls 创建对象实例
        Car car = (Car) cls.newInstance();
        System.out.println(car);

        //6、通过反射获取属性
        Field brand = cls.getField("brand");
        System.out.println(brand.get(car));

        //7、通过反射给属性赋值
        brand.set(car,"奔驰");
        System.out.println(brand.get(car));

        //8、获取所有字段属性
        System.out.println("-------------------");
        Field[] fields = cls.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
            System.out.println(field.get(car));
        }
    }
}
